package com.topwalk.datacollect.util;

import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SocketCP {

	private static final Logger LOG = LoggerFactory.getLogger(SocketCP.class);

	// map<ip_port, socketConnPool>
	public static Map<String, LinkedBlockingQueue<Socket>> SOCKET_QUEUE = new HashMap<String, LinkedBlockingQueue<Socket>>();

	/**
	 * 创建socket连接池
	 * @param ip
	 * @param port
	 * @param poolSize
	 * @throws Exception 
	 */
	public static void create(String ip, int port, int poolSize) throws Exception {
		// 初始化socket连接池
		String key = ip + "_" + port;
		LinkedBlockingQueue<Socket> socketCP = SOCKET_QUEUE.get(key);
		if (socketCP == null) {
			socketCP = new LinkedBlockingQueue<Socket>();
			SOCKET_QUEUE.put(key, socketCP);
			for (int i = 0; i < poolSize; i++) {
				try {
					Socket socket = new Socket(ip, port);
					socketCP.put(socket);
				} catch (Exception e) {
					LOG.error("与" + ip + ":" + port + "建立连接失败！");
					throw e;
				}
			}
		}
	}
	
}
